<template>
  <div class="login">
    <van-tabs v-model="active">
  <van-tab title="手机号码登录">
     <van-form @submit="phoneLogin">
  <van-field
    v-model.trim="phone"
    name="phone"
    label="手机号码"
    placeholder="请输入手机号码"
    :rules="[{ required: true, message: '请填写手机号码' }]"
  />
  <van-field
      v-model="code"
      name="code"
      center
      clearable
      label="短信验证码"
      placeholder="请输入短信验证码"
      :rules="[{ required: true, message: '请填写验证码' }]"
    >
  <template #button>
    <van-button size="small" type="info" native-type="button" @click="handleGetCode">发送验证码</van-button>
  </template>
</van-field>
  <div style="margin: 16px;">
    <van-button round block type="danger" native-type="submit">登录</van-button>
  </div>
</van-form>
  </van-tab>

  <van-tab title="账号登录">
    <van-form @submit="usernameLogin">
  <van-field
    v-model="username"
    name="用户名"
    label="用户名"
    placeholder="用户名"
    :rules="[{ required: true, message: '请填写用户名' }]"
  />
  <van-field
    v-model="password"
    type="password"
    name="密码"
    label="密码"
    placeholder="密码"
    :rules="[{ required: true, message: '请填写密码' }]"
  />
  <div style="margin: 16px;">
    <van-button round block type="info" native-type="submit">提交</van-button>
  </div>
</van-form>
  </van-tab>
</van-tabs>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { getCode } from '@/api/user'
export default {
  name: 'Login',
  data() {
    return {
      active: '',
      username: '',
      password: '',
      phone: '18585449235',
      code: '',
    }
  },
  methods: {
    async handleGetCode() {
      if (this.phone === '') {
        Toast.fail({
          message: '请输入电话号码',
          duration: 500,
        })
        return
      }
      try {
        // 根据手机号获取验证码
        const data = await getCode(this.phone)
        console.log('data', data)
        this.code = data.code
      } catch (error) {
        console.error(error)
      }
    },
    usernameLogin(values) {
      console.log('submit', values)
    },
    async phoneLogin() {
    //  this.$store.commit() 调用mutations方法
      const success = await this.$store.dispatch('user/loginAction', { phone: this.phone, code: this.code })
      if (success) {
        this.$router.push('/home')
      } else {
        Toast.fail({
          message: '登录失败,请稍后重试!',
        })
      }
    },
  },
}
</script>

<style lang="less" scoped>

</style>
